package com.chidopi.market.bookstore.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import com.chidopi.cdf.dao.AbstractBaseDaoImpl;
import com.chidopi.market.bookstore.domain.Book2City;

public class Book2CityDaoImpl extends AbstractBaseDaoImpl<Book2City>  {
	
	private static Logger logger = LoggerFactory.getLogger(Book2CityDaoImpl.class);
	
	@Override
	public int insert(Book2City t) {
		String sql = "insert into book2city (BOOK_ID, CITY_ID, ENABLE_FLAG, SALE_PRICE, SUBSCRIBE_QUOTA ) "
				+ "values (:book_id, :city_id, :enable_flag , :sale_price, :subscribe_quota)";
		return super.execSQL(sql, t);
	}

	@Override
	public int update(Book2City t) {
		return -1;
	}

	@Override
	public int delete(Book2City t) {
		String sql = "delete from contextprovider where book_id = :book_id AND city_id = :city_id";
		return super.execSQL(sql, t);
	}

	@Override
	public List<Book2City> find(String sqlWhere, Object... args) {
		if (sqlWhere == null || sqlWhere.trim().equals("")) {
			String sql = "select a.*, b.BOOKNAME  from book2city a left join bookitems b on a.book_id = b.id order by a.city_id, a.book_id ";
			return super.simpleJdbcTemplate.query(sql, this.getRowMapper());
		} else {
			logger.debug("sqlWhere:[" + sqlWhere + "]/params:" + Arrays.asList(args).toString());
			String sql = "select a.*, b.BOOKNAME  from book2city a left join bookitems b on a.book_id = b.id where " + sqlWhere + " order by a.city_id, a.book_id ";
			logger.debug("sql: " + sql);
			List<Book2City> list = super.simpleJdbcTemplate.query(sql, this.getRowMapper(), args);
			if (list == null) {
				logger.debug("query null!!!");
			} else {
				for (Book2City book2city : list) {
					logger.debug("book_id=" + book2city.getBook_id()+ "/bookname=" + book2city.getBookname());
				}
			}
			return list;
		}
	}

	@Override
	public Book2City findById(Object id) {
		return null;
	}

	@Override
	protected String getTable() {
		return "book2city";
	}

	@Override
	protected String getSequenceName() {
		return null;
	}

	@Override
	protected RowMapper<Book2City> getRowMapper() {
		return new ParameterizedRowMapper<Book2City>(){

			@Override
			public Book2City mapRow(ResultSet rs, int rowNum)	throws SQLException {
				Book2City vo = new Book2City();
				vo.setBook_id(rs.getInt("BOOK_ID"));
				vo.setBookname(rs.getString("BOOKNAME"));
				vo.setCity_id(rs.getInt("CITY_ID"));
				vo.setEnable_flag(rs.getString("ENABLE_FLAG"));
				vo.setSale_price(rs.getFloat("SALE_PRICE"));
				vo.setSubscribe_quota(rs.getInt("SUBSCRIBE_QUOTA"));
				return vo;
			}
		};	
    }

}
